//
//  KKImagePickerModel.m
//  KKImagePickerController
//
//  Created by liaozhenming on 16/3/11.
//  Copyright © 2016年 JuniorCodingPerson. All rights reserved.
//

#import "KKImagePickerModel.h"

@implementation KKImagePickerSet

+ (instancetype)pickerSet {
    static KKImagePickerSet *pickerSet = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        pickerSet = [KKImagePickerSet new];
    });
    return pickerSet;
}

- (BOOL)kk_matchItem:(KKImageItem*)item {
    return [self kk_matchAsset: item.asset_8 delete: false];
}

- (BOOL)kk_matchAsset:(id)asset delete:(BOOL)delete {
    for (KKImageItem *item in _kk_selectedItems) {
        
        if([asset isKindOfClass: [PHAsset class]]) {
            PHAsset *currentAsset = item.asset_8;
            NSString *itemId = [(PHAsset*)currentAsset localIdentifier];
            NSString *assetId = [(PHAsset*)asset localIdentifier];
            if ([itemId isEqualToString: assetId]) {
                if (delete) {
                    [_kk_selectedItems removeObject: item];
                }
                return true;
            }
        }
    }
    return false;
}

- (void)kk_cleanAllItems {
    
    [_kk_selectedItems removeAllObjects];
}

- (void)kk_setItem:(KKImageItem*)item {
    if (item == nil) {
        return;
    }
    
    if (_kk_selectedItems == nil) {
        _kk_selectedItems = [NSMutableArray array];
    }
    
    if (![self kk_matchAsset: item.asset_8 delete: true]) {
        
        if (_kk_selectedItems.count >= _kk_maxLimit && _kk_maxLimit > 0) {
            
            [KKImagePickerManager kk_showErrorMessage: @"数量限制"];
            return;
        }
        
        [_kk_selectedItems addObject: item];
    }
}

@end
